import ModalContainer from './ModalContainer.vue'
import type { ModalOptions } from './types'
import { exposedOf, renderInBody } from '../../util'

interface ModalInstance {
  destroy(): void
}

function destroy(key: string) {
  exposedOf<InstanceType<typeof ModalContainer>>(vNode, (e) => e.destroy(key))
}

export function createModal(opt: ModalOptions): ModalInstance {
  return exposedOf<InstanceType<typeof ModalContainer>>(vNode, (e) => {
    const key = e.create(opt)
    return {
      destroy() {
        destroy(key)
      }
    }
  })!
}

const vNode = renderInBody(ModalContainer)
